import json

from imports.complexboard import *

class GameBoard:
    def __init__(self, rows, columns):
        self.data = {
            "size": [rows, columns],
            "matrix": [],
            "solution": set()
        }
    def renew(self):
        x = ComplexBoard(self.data["size"][0],self.data["size"][1])
        x.build()
        self.data["matrix"] = []
        for i in x.cell:
            self.data["matrix"].append(i.value)
        self.data["solution"] = x.solution
    def __str__(self):
        string = ""
        string += str(self.data["size"][0]) + ' ' + str(self.data["size"][1]) + '\n'
        string += str(self.data["matrix"]) + '\n'
        string += str(self.data["solution"])
        return string
    def display(self):
        if len(self.data["matrix"]) == 0:
            return ""
        string = ""
        for i in range(self.data["size"][0]):
            for j in range(self.data["size"][1]):
                string += str(self.data["matrix"][i*self.data["size"][1]+j]) + " "
            string = string[:-1] + '\n'
        string = string[:-1] + "\n\n"
        for i in range(self.data["size"][0]):
            for j in range(self.data["size"][1]):
                if i*self.data["size"][1]+j in self.data["solution"]:
                    string += "■ "
                else:
                    string += "□ "
            string = string[:-1] + '\n'
        print(string[:-1])
    def json_import(self, k):
        file = 'data\\gameboard' + str(k) +'.gblog'
        f = open(file, "r")
        self.data = json.loads(f.read())
        f.close()
    def export(self, k):
        string = json.dumps(self.data).replace(' ','')
        file = 'data\\gameboard' + str(k) + '.gblog'
        try:
            f = open(file, "x")
            f.write(string)
            f.close()
            return True
        except FileExistsError as e:
            return False